package com.kai.dao.impl;

import com.kai.dao.EmpDao;
import com.kai.pojo.Emp;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Created By ShaoXikai on 2022/5/21
 */
public class EmpDaoImpl implements EmpDao {

    static class Session {
        private static SqlSessionFactory sqlSessionFactory;

        static {
            try {
                InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public static SqlSession getSqlSession() {
            return sqlSessionFactory.openSession();
        }
    }

    @Override
    public int addEmp(Emp emp) {
        SqlSession sqlSession = Session.getSqlSession();
        EmpDao mapper = sqlSession.getMapper(EmpDao.class);
        int resp = mapper.addEmp(emp);
        sqlSession.commit();
        sqlSession.close();
        return resp;
    }

    @Override
    public int deleteById(Long id) {
        SqlSession sqlSession = Session.getSqlSession();
        EmpDao mapper = sqlSession.getMapper(EmpDao.class);
        int resp = mapper.deleteById(id);
        sqlSession.commit();
        sqlSession.close();
        return resp;
    }

    @Override
    public int updateById(Emp emp) {
        SqlSession sqlSession = Session.getSqlSession();
        EmpDao mapper = sqlSession.getMapper(EmpDao.class);
        int resp = mapper.updateById(emp);
        sqlSession.commit();
        sqlSession.close();
        return resp;
    }

    @Override
    public List<Emp> selectList() {
        SqlSession sqlSession = Session.getSqlSession();
        EmpDao mapper = sqlSession.getMapper(EmpDao.class);
        return mapper.selectList();
    }

    @Override
    public Emp selectById(Long id) {
        SqlSession sqlSession = Session.getSqlSession();
        EmpDao mapper = sqlSession.getMapper(EmpDao.class);
        return mapper.selectById(id);
    }
}
